//引入创建路由的方法以及采用的路由模式的方法（Hash还是History）
import { createRouter, createWebHashHistory } from "vue-router"
const routes = [          //创建路由组，配置路由的映射关系
  { path: "/", redirect: "/home", meta: { title: "首页" } },
  { path: "/home", name: "home", component: () => import("@/views/Home.vue"), meta: { title: "首页" } },
  { path: "/list", name: "list", component: () => import("@/views/List.vue"), meta: { title: "列表页" } },
  { path: "/details", name: "details", component: () => import("@/views/Details.vue"), meta: { title: "详情页" } },
  { path: "/cart", name: "cart", component: () => import("@/views/Cart.vue"), meta: { title: "购物车" } },
  {
    path: "/order", name: "order", component: () => import("@/views/Order.vue"), meta: { title: "订单页" }, children: [
      { path: "", component: () => import("@/components/OrderList.vue"), meta: { title: "全部订单" } }, //默认加载子路由
      { path: "orderlist", component: () => import("@/components/OrderList.vue"), meta: { title: "订单列表" } }
    ]
  },
  { path: "/login", name: "login", component: () => import("@/views/Login.vue"), meta: { title: "登录" } },
  { path: "/regiest", name: "regiest", component: () => import("@/views/Regiest.vue"), meta: { title: "注册" } }
]

//创建一个路由实例
const router = createRouter({
  history: createWebHashHistory(),    //指定采用的路由模式：Hash
  routes                             //加载创建的路由组
})

//全局前置守卫
router.beforeEach((to, from, next) => {
  let hasLogin = sessionStorage.getItem("token"); //从session中获取是否已经登录过的信息
  if (hasLogin) {            //如果已经登录
    next()                  //正常进入，比如到首页或其他页面
  } else {                   //未登录
    if (to.path === "/login") {    //如果要进入的是登录页，从登录页正常进入
      next();
    } else if (to.path == "/cart" || to.path == "/order" || to.path == "/user") {                   //如果要进入的不是登录页，则从登录页进入             
      next("/login")
    } else {
      next()
    }
  }
})

//导出router模块
export default router

